package models

import (
	"ssdevice/common/dto"
	"time"

	"gitee.com/sansaniot/ssiot-core/httpmvc/model"
	"gorm.io/gorm"
	"ssdevice/common/utils"
)

// SysDeviceTag 设备与标签关联表
type SysDeviceTag struct {
	Id         string        `json:"id" gorm:"primaryKey;type:varchar(255);comment:关联ID"`
	DeviceSn   string        `json:"deviceSn" gorm:"type:varchar(255);index;comment:设备SN"`
	TagId      string        `json:"tagId" gorm:"type:varchar(255);index;comment:标签ID"`
	CreateTime dto.LocalTime `json:"createTime" gorm:"type:timestamptz(6);default:now();comment:创建时间"`
	UpdateTime dto.LocalTime `json:"updateTime" gorm:"type:timestamptz(6);default:now();comment:更新时间"`
	model.Model
}

func (e *SysDeviceTag) TableName() string {
	return "sys_dev_tag_r"
}

// DeleteByDeviceSn 根据设备SN删除所有关联
func (e *SysDeviceTag) DeleteByDeviceSn(deviceSn string) error {
	return e.Orm.Where("device_sn = ?", deviceSn).Delete(e).Error
}

// DeleteByTagId 按tagId删除关联
func (e *SysDeviceTag) DeleteByTagId(tagId string, devSn string) error {
	return e.Orm.Where("tag_id =? and device_sn = ?", tagId, devSn).Delete(e).Error
}

// FindByDeviceSn 根据设备SN查询所有关联的标签ID
func (e *SysDeviceTag) FindByDeviceSn(deviceSn string) ([]string, error) {
	var tagIds []string
	err := e.Orm.Model(e).Where("device_sn = ?", deviceSn).Pluck("tag_id", &tagIds).Error
	return tagIds, err
}

// BatchCreateDeviceTagAssociations 批量创建设备与标签的关联
func (e *SysDeviceTag) BatchCreateDeviceTagAssociations(tx *gorm.DB, deviceSn string, tagIds []string) error {
	if tx == nil {
		tx = e.Orm
	}

	// 删除现有关联
	if err := tx.Where("device_sn = ?", deviceSn).Delete(e).Error; err != nil {
		return err
	}

	// 创建新关联
	if len(tagIds) > 0 {
		associations := make([]SysDeviceTag, 0, len(tagIds))
		now := dto.LocalTime(time.Now())

		for _, tagId := range tagIds {
			associations = append(associations, SysDeviceTag{
				Id:         utils.SimpleUUID(),
				DeviceSn:   deviceSn,
				TagId:      tagId,
				CreateTime: now,
				UpdateTime: now,
			})
		}

		return tx.Create(&associations).Error
	}

	return nil
}
